package com.nettytime.util.testjiebaonianbaos;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;

@Slf4j
public class NettyClient {

    Bootstrap bootstrap = null;
    EventLoopGroup group = new NioEventLoopGroup();
    public void connect(final String host, final int port) throws Exception {
        ChannelFuture future = null;
        try {
            if (bootstrap == null) {
                bootstrap = new Bootstrap();
            }
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    //TCP_NODELAY就是用于启用或关于Nagle算法。如果要求高实时性，有数据发送时就马上发送，就将该选项设置为true关闭Nagle算法；如果要减少发送次数减少网络交互，就设置为false等累积一定大小后再发送。默认为false。
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChildClientFixedLengthChannelHandler());
            future = bootstrap.connect(host, port).sync();
            future.channel().closeFuture().sync();
            //加一个监听器，断线重连
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if(channelFuture.isSuccess()){
                        System.out.println("连接服务端成功");
                    }else{
                        System.out.println("每隔2s重连....");
                        channelFuture.channel().eventLoop().schedule(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    connect(host,port);
                                } catch (Exception e) {
                                    log.error("重连报错:{}",e.getMessage(),e);
                                }
                            }
                        },2, TimeUnit.SECONDS);
                    }
                }
            });
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        try {
            new NettyClient().connect("localhost", 8080);
        } catch (Exception e) {
            log.error("连接服务器异常:{}",e.getMessage(),e);
        }
    }
}
